from fastapi import APIRouter, Request, status, WebSocket, WebSocketDisconnect
import os
from api.application.utils.llm import deepseek
from api.application.utils.logs import getLogger
from api.application import settings
from .models import Session, History

logger = getLogger(os.environ.get('APP_NAME'))

app = APIRouter()


@app.websocket("/index")
async def index(websocket: WebSocket):
    await websocket.accept()
    redis = websocket.app.state.redis
    try:
        while True:
            data = await websocket.receive_json()
            if data.get('action') == 'login':
                print("login_message:::", data.get('message'))
            elif data.get('action') == 'chat':
                user_id = 10
                session_id = await redis.get(f'session_{user_id}')
                if not session_id:
                    session = await Session.filter(user__id=6).order_by('-id').first()
                    if not session:
                        session = await Session.create(name="默认", user=user_id)
                    session_id = session.id
                    await redis.set(f"session_{user_id}", session_id)
                history = await History.filter(session_id=session_id).all().order_by('-id').limit(100)
                history.append(data.get('message'))
                print("history:::",history)
                print("requestdata:::", data)
                print(data.get('message'))
                print("base_url:::", settings.DEEPSEEK.get('baseurl'))
                print("api_key:::", settings.DEEPSEEK.get('apikey') )
                print("model:::", settings.DEEPSEEK.get('model'))
                print("prop:::", data.get('message'))
                print("history_list:::", history)
                ai_response = deepseek(
                    base_url=settings.DEEPSEEK.get('baseurl'),
                    api_key=settings.DEEPSEEK.get('apikey'),
                    model=settings.DEEPSEEK.get('model'),
                    prop=data.get('message'),
                    history_list=history
                )

                print(ai_response)
                message = {
                    'action': 'chat',
                    'type': 'text',
                    'message': ai_response.content
                }
                await websocket.send_json(message)

            elif data.get('action') == 'session':
                pass

    except WebSocketDisconnect:
        print('客户端断开连接了')

    except Exception as e:
        print(e)

# BASE_URL="https://api.deepseek.com/v1",
# API_KEY="sk-0b68d69373844ad18ea2f95b277797b7",
# MODEL="deepseek-reasoner"
# def deepseek(base_url, api_key, prop, history_list=None, model="deepseek-reasoner"):


# DEEPSEEK = {
#     'base_url': os.environ.get('BASE_URL'),
#     'api_key': os.environ.get('API_KEY'),
#     'model': os.environ.get('MODEL')
# }
